
#import "ZallAutoScrollView.h"
#import "ZallScheduleManager.h"
#import "UIImageView+WebCache.h"
#import "NSObject+ZallAdditions.h"

#define SCROLL_CURRENT_PAGES    3

static NSString * ZallAutoScrollViewScheduledKey = @"ZallAutoScrollViewScheduledKey";

@interface ZallAutoScrollView () <UIScrollViewDelegate>

@property (assign, nonatomic) NSInteger totalPage;
@property (assign, nonatomic) NSInteger curPage;
@property (assign, nonatomic) CGRect scrollFrame;
@property (strong, nonatomic) UIImageView *curImageView;
@property (strong, nonatomic) NSMutableArray *curImageUrls;

- (NSInteger)validPageValue:(NSInteger)value;
- (void)reloadData;

- (NSArray *)getDisplayImagesWithCurpage:(NSInteger)page;

/**
 *  @brief  修改自动滑动的key
 */
@property (copy, nonatomic) NSString *autoScollViewScheduledKey;

@end

@implementation ZallAutoScrollView
@synthesize scrollView = _scrollView;

- (void)dealloc {
    
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if(self) {
        self.backgroundColor = [UIColor whiteColor];
        _autoTimeInterval = 5.0f;
        _autoScroll = NO;
        _curImageUrls = [[NSMutableArray alloc] initWithCapacity:0];
        _imageUrls = [[NSArray alloc] init];
        _totalPage = self.imageUrls.count;
        _curPage = 1;
        self.autoScollViewScheduledKey = @"ZallAutoScrollViewScheduledKey";
        [self addSubview:self.scrollView];
        _pageCtrl = [[UIPageControl alloc] init];
        [self addSubview:self.pageCtrl];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.scrollView.frame = self.bounds;
    self.scrollFrame = self.scrollView.frame;
    self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * SCROLL_CURRENT_PAGES, self.scrollView.frame.size.height);
    self.pageCtrl.frame = CGRectMake(0, self.bounds.size.height * 0.75f, self.bounds.size.width, self.bounds.size.height * 0.25f);
}

#pragma mark - getter
- (UIScrollView *)scrollView {
    if(!_scrollView) {
        _scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        _scrollView.backgroundColor = [UIColor clearColor];
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.pagingEnabled = YES;
        _scrollView.delegate = self;
    }
    self.scrollFrame = _scrollView.frame;
    _scrollView.contentSize = CGSizeMake(_scrollView.frame.size.width * SCROLL_CURRENT_PAGES, _scrollView.frame.size.height);
    return (_scrollView);
}

- (NSArray *)getDisplayImagesWithCurpage:(NSInteger)page {
    NSInteger pre = [self validPageValue:_curPage - 1];
    NSInteger last = [self validPageValue:_curPage + 1];
    if([_curImageUrls count] != 0) {
        [_curImageUrls removeAllObjects];
    }
    [_curImageUrls safeAddObject:[self.imageUrls safeObjectAtIndex:pre - 1]];
    [_curImageUrls safeAddObject:[self.imageUrls safeObjectAtIndex:_curPage - 1]];
    [_curImageUrls safeAddObject:[self.imageUrls safeObjectAtIndex:last - 1]];
    return (_curImageUrls);
}

- (NSInteger)validPageValue:(NSInteger)value {
    if(value == 0) {
        value = _totalPage;
    }
    if(value == _totalPage + 1) {
        value = 1;
    }
    return (value);
}
#pragma mark -

#pragma mark - setter
- (void)setImageUrls:(NSArray *)imageUrls {
    BOOL pauto ;//= self.autoScroll;
    self.autoScroll = NO;
    [self willChangeValueForKey:@"imageUrls"];
    _imageUrls = [imageUrls mutableCopy];
    [self didChangeValueForKey:@"imageUrls"];
    _curPage = 1;
    _totalPage = self.imageUrls.count;
    self.pageCtrl.numberOfPages = _totalPage;
    [self reloadData];
    
    /*
     start by lizhiquan
        修改图片展示的处理  2017年05月31日14:28:35
     end by lizhiquan
     */
//    //如果图片数量小于2，则不显示指示点且不自动滚动也不能滚动
    self.scrollView.scrollEnabled = (_totalPage > 1);
    self.pageCtrl.hidden = (_totalPage < 2);
    if(_totalPage < 2) {
        pauto = NO;
    }else{
        pauto = YES;
    }
    
    self.autoScroll = pauto;
}

- (void)setAutoScroll:(BOOL)autoScroll {
    [self willChangeValueForKey:@"autoScroll"];
    _autoScroll = autoScroll;
    [self didChangeValueForKey:@"autoScroll"];
    if(_autoScroll) {
        __weak typeof(self) weak_self = self;
        [[ZallScheduleManager manager] addScheduleBlock:^(void) {
            [weak_self startAutoScroll];
        } interval:_autoTimeInterval forKey:self.autoScollViewScheduledKey];
    } else {
        [[ZallScheduleManager manager] removeScheduleBlockForKey:self.autoScollViewScheduledKey];
    }
}

- (void)setAutoTimeInterval:(NSTimeInterval)autoTimeInterval {
    [self willChangeValueForKey:@"autoTimeInterval"];
    _autoTimeInterval = autoTimeInterval;
    [self didChangeValueForKey:@"autoTimeInterval"];
    [self setAutoScroll:_autoScroll];
}

- (void)setType:(KAutoScollViewType)type {
    [self willChangeValueForKey:@"type"];
    _type = type;
    [self didChangeValueForKey:@"type"];
    NSString *keyType = @"KAutoScollViewTransoprtType";
    if (type == KAutoScollViewCityWideType) {
        keyType = @"KAutoScollViewCityWideType";
    }
    self.autoScollViewScheduledKey = [NSString stringWithFormat:@"%@%@",keyType,ZallAutoScrollViewScheduledKey];
}
#pragma mark -

#pragma mark - actions
- (void)startAutoScroll {
    CGSize bdSize = self.bounds.size;
    CGRect nextRect = CGRectMake(bdSize.width * (SCROLL_CURRENT_PAGES - 1), 0, bdSize.width, bdSize.height);
    [self.scrollView scrollRectToVisible:nextRect animated:YES];
    
    NSArray *subViews = [self.scrollView subviews];
    if(subViews && [subViews isKindOfClass:[NSArray class]] && [subViews count] > _curPage && _curImageUrls && [_curImageUrls count] > _curPage) {
        UIView *vw = [subViews safeObjectAtIndex:_curPage];
        id imgObj = [_curImageUrls safeObjectAtIndex:_curPage];
        if(vw && [vw isKindOfClass:[UIImageView class]] && imgObj) {
            UIImageView *imgVw = (UIImageView *)vw;
            if ([imgObj isKindOfClass:[NSString class]] && [imgObj length] > 0) {
                [imgVw sd_setImageWithURL:[NSURL URLWithString:imgObj] placeholderImage:[UIImage imageNamed:@"img_default"]];
            }else if ([imgObj isKindOfClass:[NSURL class]]) {
                [imgVw sd_setImageWithURL:imgObj placeholderImage:[UIImage imageNamed:@"img_default"]];
            }else if ([imgObj isKindOfClass:[UIImage class]]){
                imgVw.image = imgObj;
            }else{
                imgVw.image = [UIImage imageNamed:@"img_default"];
            }
            
        }
    }
    
    if (_delegate && [_delegate respondsToSelector:@selector(autoScrollViewDelegate:didScrollImageView:)]) {
        [_delegate autoScrollViewDelegate:self didScrollImageView:_curPage];
    }
}

- (void)reloadData {
    NSArray *subViews = [self.scrollView subviews];
    if([subViews count] != 0) {
        [subViews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    }
    [self getDisplayImagesWithCurpage:_curPage];
    for (NSInteger i = 0; i < SCROLL_CURRENT_PAGES; i++) {
        id imgObj = [_curImageUrls safeObjectAtIndex:i];
        NSURL *imgUrl = nil;
        UIImage *image = nil;
        if([imgObj isKindOfClass:[NSString class]]) {
            imgUrl = [NSURL URLWithString:imgObj];
        } else if([imgObj isKindOfClass:[NSURL class]]){
            imgUrl = (NSURL *)imgObj;
        } else if([imgObj isKindOfClass:[UIImage class]]){
            image = (UIImage *)imgObj;
        }
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.scrollFrame];
        imageView.backgroundColor = [UIColor whiteColor];
        imageView.userInteractionEnabled = YES;
        if (imgUrl) {
            [imageView sd_setImageWithURL:imgUrl placeholderImage:[UIImage imageNamed:self.imagePlaceholder ? : @"img_default"]];
        }else if(image){
            [imageView setImage:image];
        }
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
        [imageView addGestureRecognizer:singleTap];
        imageView.frame = CGRectOffset(imageView.frame, self.scrollFrame.size.width * i, 0);
        [self.scrollView addSubview:imageView];
    }
    [self.scrollView setContentOffset:CGPointMake(self.scrollFrame.size.width, 0)];
    self.pageCtrl.currentPage = _curPage - 1;
}

- (void)handleTap:(UITapGestureRecognizer *)tap {
    if (_delegate && [_delegate respondsToSelector:@selector(autoScrollViewDelegate:didSelectImageView:)]) {
        [_delegate autoScrollViewDelegate:self didSelectImageView:_curPage];
    }
}
#pragma mark -

#pragma mark - <UIScrollViewDelegate>
- (void)scrollViewDidScroll:(UIScrollView *)aScrollView {
    NSInteger x = aScrollView.contentOffset.x;
    if(x >= ((SCROLL_CURRENT_PAGES - 1) * self.scrollFrame.size.width)) {
        _curPage = [self validPageValue:_curPage + 1];
        [self reloadData];
    }
    if(x <= 0) {
        _curPage = [self validPageValue:_curPage - 1];
        [self reloadData];
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [[ZallScheduleManager manager] removeScheduleBlockForKey:self.autoScollViewScheduledKey];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self setAutoScroll:self.autoScroll];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)aScrollView {
    [self.scrollView setContentOffset:CGPointMake(self.scrollFrame.size.width, 0) animated:YES];
}
#pragma mark -

@end
